﻿
import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { imageBaseUrl, isImageFile, downloadfun, IDeletePPEFile, getBrowserInfo, easyCopy } from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const generateh = (text, isShort) => {
        if (isShort) {
            return h('div', {
                style: "width:200px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis; -o-text-overflow: ellipsis;cursor:pointer"
            }, { default: () => text })
        } else {
            return h('div', {
                style: "width:100px;height:auto;"
            }, { default: () => text })
        }

    }
    const data = reactive({
        pdfOpen: false,
        pdfurl: "",

        messageTest: "",
        proxy: "",
        imgUrl: "",
        previewShow: false,
        edituploadList: [],
        uploadLock:false,
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        itemRender: (data) => {

            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })


            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => methods.btnDelete(data)

            }, { default: () => [deleteBtn] })


            var btns = btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url) ? previewBtn : null,
                    downloadBtn,
                    params.opType.value!=2? FDBtn:null,
                ]
            })

            return h('div', { style: 'margin-top:10px; width:100%;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        cindex: -1,
        ccindex: -1,
        cIsEdit: false,
        editres: "",
        templateOpen:false,
        queryParams: {
            ProductName: null,
            TypeId: null,
        },
        cid: "",
        shadowShow:true,
        opType: 0,
        FormRule: {
            name: { required: true, message: '请填写用品名称', trigger: 'change' },
            type: { required: true, message: '请选择类型', trigger: 'change' },
            unit: { required: true, message: '请填写单位', trigger: 'change' },
        },
        configData: {
            name: null,
            type: null,
            unit: null,
            Remark:null,
            specification: [{
                name: null,
                tags: [
                    {label:null}
                ],
                inputVisible: false,
                inputValue: '',
                delIds: [],
                delTagsIds: []
            }],
            Description: null,
            options: [],

        }, 
        pagination: {
            total: 0,
            current: 1,
            loading: false,
            pageSize: 10,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗

        },
        columns: [
            {
                title: '序号',
                dataIndex: 'no',
                key: 'no',
                align: 'center',
                width: 80,
                customRender: ({ index }) => {
                    return (params.pagination.value.current - 1) * params.pagination.value.pageSize + index + 1
                },
            },
            {
                title: '用品名称',
                dataIndex: 'ProductName',
                key: 'ProductName',
                align: 'center',
                width: 180,

            },
            {
                title: '类型',
                dataIndex: 'TypeName',
                key: 'TypeName',
                align: 'center',
                width: 150,
       
            },
            {
                title: '单位',
                dataIndex: 'Unit',
                key: 'Unit',
                align: 'center',
                width: 90,
            },
            {
                title: '规格',
                dataIndex: 'AttrList',
                key: 'AttrList',
                width: 200,
                align: 'center',
                customRender: function ({ text }) {
                    let divs = text.map((e,i) => {
                        return h('div', {
                            style: `max-width:300px;
                            overflow-x:scroll;
                            display: flex;
                            margin:0 auto;
                          `
                            
                        }, {
                            default: () => `${e.AttributeName} : ${e.ItemList.map(es => es.AttributeValue).toString()}` })
                    })
                    return h('div', {
                        style: `width: 200px;`
                    },
                        [...divs]
                    );
         
           
                }
            },
            {
                title: '防护功能',
                dataIndex: 'Remark',
                key: 'Remark',
                align: 'center',
                width: 200,
                customRender: function ({ text, record, index, column }) {

                 let hdiv = h('div', {
                        style: `max-width: 400px;
                      
                          `

                    }, {
                     default: () => text
                    })
                


                    return h(antd.Popover, {
                        title: '防护功能',
                        content: hdiv
                    }, () => [[generateh(text, true)]]);
                },

          
            },
            //{
            //    title: '备注',
            //    dataIndex: 'Description',
            //    key: 'Description',
            //    align: 'center',
            //    width: 200,
            //    customRender: function ({ text, record, index, column }) {

            //        let hdiv = h('div', {
            //            style: `width: 100px;
                      
            //              `

            //        }, {
            //            default: () => text
            //        })



            //        return h(antd.Popover, {
            //            title: '备注',
            //            content: hdiv
            //        }, () => [[generateh(text, true)]]);
            //    },


            //},
            {
                title: '图片',
                dataIndex: 'ImagList',
                key: 'ImagList',
                align: 'center',
                customRender: function ({ text, record, index, column }) {

                    let divs = text.map((e, i) => {
                        return h(antd.Image, {
                            width: '100px',
                            height: '100px',
                            src: e.FilePath

                        }, {
                            default: () =>[]
                        })
                    })

     
                    let s = h(antd.Space, {
                        style: `width:auto;`
                    },
                        { default: () => [...divs] }
                    );

                    let f = h(antd.ImagePreviewGroup , {
                        style: `width: 100%;`
                    },
                        {   default: () => [s]}
                    );
                    return f

                }
            },
            {
                title: '操作',
                key: 'action',
                align: 'center',
                fixed: 'right',
                width: 80,
                customRender: function ({ text, record, index, column }) {
      
                    const delBtn = h(antd.Button, {
                        style: 'margin-right:4px',
                        type: "link",
                        danger:true
                    }, { default: () => '删除' })

                    const fDelBtn = h(antd.Popconfirm, {
                        title: `提示：配置【${record.ProductName}】，删除后将无法恢复，请您确认。 `,
                        onConfirm: () => {
                            methods.DeleteEquBasicInfo(record)
                        }

                    }, { default: () => delBtn })


                    const modifyBtn = h(antd.Button, {
                        style: 'margin-right:4px',
                        type: "link",
                        onClick: () => {
                            params.opType.value = 1;
                            params.cid.value = record.Id;
                            methods.GetEquBasicInfo(record);
                        }
                    }, { default: () => '编辑' })


                    const settingBtn = h(antd.Button, {
                        style: 'margin-right:4px',
                        type: "link",
                        onClick: () => {
                            params.opType.value = 3;
                            params.cid.value = record.Id;
                            methods.handleSettingThing(record);
                        }
                    }, { default: () => '编码配置' })

                    const detailBtn = h(antd.Button, {
                        style: 'margin-right:4px',
                        type: "link",
                        onClick: () => {
                            params.opType.value = 2
                            methods.GetEquBasicInfo(record)
                        }
                    }, { default: () => '详情' })

                    return h('div', {
                    },
                        () => [modifyBtn, fDelBtn, settingBtn, detailBtn ]
                    );

                }
            },
        ],
        dataSource: [],
    })
    let params = toRefs(data)
    const methods = {

        handleCancel: () => {
            params.uploadImg.value.previewVisible = false;
            params.uploadImg.value.previewTitle = '';
        },
        getBase64: (file) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            })
        },
        handlePreview: async (file) => {
            if (!file.url && !file.preview) {
                file.preview = (await methods.getBase64(file.originFileObj));
            }
            params.uploadImg.value.previewImage = file.url || file.preview;
            params.uploadImg.value.previewVisible = true;
            params.uploadImg.value.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
        },
        handleSettingThing(record) {
            window.location.href = `/PPE/SpecsAndConfigs?id=${record.Id}`
 
        },
        handleQuery: () => {
            methods.getTableList(true)
        },

        setVisible: (value) => {
            params.previewShow.value = value;
        },
        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url

                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            params.uploadLock.value = true
            downloadfun(name, url).finally(() => {
                params.uploadLock.value = false
            })

        },
        btnDelete: (e) => {
            const { FileId, uid } = e.file
            if (FileId) {

                IDeletePPEFile(Request, FileId).then(res => {


                    params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(es => es.uid != uid)



                    if (params.opType.value == 1) {

                        let index = params.edituploadList.value.findIndex(e => e == FileId)
                        if (index != -1) {
                            params.edituploadList.value.splice(index, 1)
                        }
          

                    }

                })
            }
        },
        testclick: () => {
            for (let e of params.configData.value.specification) {
                e.inputVisible = false
            }
        },
        handletest: (e) => {
            if (params.configData.value.specification[params.cindex.value].tags[params.ccindex.value]?.label) {
                params.configData.value.specification[params.cindex.value].tags[params.ccindex.value].label = params.editres.value
                params.cIsEdit.value = false
            }
       
        },

        enter: (index) => {

            params.cindex.value = index
            //params.configData.value.specification[params.cindex.value].inputVisible = true;
            //params.cIsEdit.value = true

            //setTimeout(() => {
            //    params.proxy.value.$refs[`addInput${params.cindex.value}`][0].focus()
            //}, 300)
        },

        handleDbclick: (a, b) => {
  
            params.cindex.value = a
            params.ccindex.value = b
            params.editres.value = params.configData.value.specification[params.cindex.value].tags[params.ccindex.value].label
            params.cIsEdit.value = true
            setTimeout(() => {
                params.proxy.value.$refs[`cctest${params.cindex.value}`][0].focus()
            }, 300)

        },


        GetEquBasicInfo: (record) => {
            params.configData.value = Object.assign({}, params.configData.value, {
                name: null,
                type: null,
                unit: null,
                Description:null,
                Remark:null,
                specification: [{
                    name: null,
                    tags: [
                        /*   { label:null }*/
                    ],
                    inputVisible: false,
                    inputValue: '',
                }],
            })
            params.uploadImg.value.fileList = []

            params.pagination.value.loading=true
            Request({
                url: "/PPE/GetEquBasicInfo",
                method: 'post',
                params: {
                    Id: record.Id,
                },
            }).then(res => {

                params.templateOpen.value = true
               
                params.configData.value.type = res.Data.TypeId
                params.configData.value.name = res.Data.ProductName
                params.configData.value.Remark = res.Data.Remark
                params.configData.value.Description = res.Data.Description
                
                params.configData.value.unit = res.Data.Unit
                params.configData.value.specification = res.Data.AttrList.map(e => {
                    return {
                        name: e.AttributeName,
                        tags: e.ItemList.map(es => {

                            return {
                                label: es.AttributeValue,
                                value: es.Id
                            }
                        }),
                        Id: e.Id
                    }
                })

                params.uploadImg.value.fileList = res.Data.ImagList && res.Data.ImagList.map(e => {
                    return {
                        url: e.url ? e.url : imageBaseUrl + e.FilePath.split('../..')[1],
                        name: e.FileName,
                        uid: e.uid,
                        FileId: e.FileId
                    }
                })


                methods.scrollt()

            }).finally(() => {
                params.pagination.value.loading = false
            })
        },




        DeleteEquBasicInfo: (record) => {
            Request({
                url: "/PPE/DeleteEquBasicInfo",
                method: 'post',
                params: {
                    Id: record.Id,
                },
            }).then(res => {
                methods.getTableList(true)
                params.messageTest.value.info(res.Msg);
            })
        },
   

        handleClose(removedTag, removedIndex) {



            if (removedTag.value) {
                const tags = easyCopy(params.configData.value.specification[params.cindex.value].tags).filter(tag => {
                    return tag.value !== removedTag.value
                });


                params.configData.value.specification[params.cindex.value].tags = tags;


                if (removedTag.value) {
                    params.configData.value.specification[params.cindex.value].removedItemsIds ? params.configData.value.specification[params.cindex.value].removedItemsIds.push(removedTag.value) : params.configData.value.specification[params.cindex.value].removedItemsIds = [removedTag.value];
                }
            } else {
                const tags = easyCopy(params.configData.value.specification[params.cindex.value].tags).filter(tag => {
                    return tag.label !== removedTag.label
                });


                params.configData.value.specification[params.cindex.value].tags = tags;


                if (removedTag.value) {
                    params.configData.value.specification[params.cindex.value].removedItemsIds ? params.configData.value.specification[params.cindex.value].removedItemsIds.push(removedTag.value) : params.configData.value.specification[params.cindex.value].removedItemsIds = [removedTag.value];
                }
            }

   

          
        },

        showInput() {
       
            params.configData.value.specification[params.cindex.value].inputVisible = true;
            params.cIsEdit.value = true

            setTimeout(() => {
                params.proxy.value.$refs[`addInput${params.cindex.value}`][0].focus()
            }, 300)

      
        },

         handleInputConfirm  () {
             const inputValue = params.configData.value.specification[params.cindex.value].inputValue;
             let tags = params.configData.value.specification[params.cindex.value].tags;
             if (inputValue && tags.indexOf(inputValue) === -1) {
                 tags = [...tags, { label: inputValue } ];
            }
             Object.assign(params.configData.value.specification[params.cindex.value], {
                tags,
                inputVisible: false,
                inputValue: '',
             });
             params.cIsEdit.value = false
         
        },

        addItemConfig:()=> {
            params.configData.value.specification.push({
                name: null,
                tags: [],
                inputVisible: false,
                inputValue: '',
            })
            methods.scrollt()
        },
        delItemConfig: (i) => {

            if (params.opType.value == 1) {
                if (params.configData.value.specification[i].Id) {
                    params.configData.value.removedIds ? params.configData.value.removedIds.push(params.configData.value.specification[i].Id) : params.configData.value.removedIds = [params.configData.value.specification[i].Id]
                }
             
            }
                params.configData.value.specification.splice(i, 1)
            
  
        
        },
 
        addConfig: () => {
            params.opType.value = 0
            params.templateOpen.value = true
            methods.scrollt()
            params.configData.value = Object.assign({}, params.configData.value, {
                name: null,
                type: null,
                unit: null,
                Remark: null,
                Description: null,
                specification: [{
                    name: null,
                    tags: [
                     /*   { label:null }*/
                      ],
                    inputVisible: false,
                    inputValue: '',
                }],
            })
            params.uploadImg.value.fileList=[]
        },
        handleTableChange: (page) => {
            const { current, pageSize } = page
            params.pagination.value.current = current;
            params.pagination.value.pageSize = pageSize;
            methods.getTableList()
        },
        getTableList: (isRresh) => {
            if (isRresh) {
                params.pagination.value.current = 1
            }
            Request({
                url: "/PPE/GetEquBasicPageList",
                method: 'post',
                params: {
                    page: params.pagination.value.current,
                    pageSize: params.pagination.value.pageSize,
                    ...params.queryParams.value
                },
            }).then(res => {
                params.dataSource.value= res.Data.Data
                params.pagination.value.total = res.Data.TotalItemCount
                params.pagination.value.loading = false
                params.templateOpen.value=false
                
            })
        },
        EditEquBasicInfo: () => {


            for (let list of params.configData.value.specification) {

                if (!list.name) {
                    return   params.messageTest.value.info('请检查规格名称是否全部填写');
                } else if (list.tags.length == 0) {
                    return  params.messageTest.value.info('请检查规格是否全部添加');
                }

            }



            let model = {

                "Id": params.cid.value,
                "ProductName": params.configData.value.name,
                "TypeId": params.configData.value.type,
                Remark: params.configData.value.Remark,
                Description: params.configData.value.Description,
                "Unit": params.configData.value.unit,
                "FileList": params.edituploadList.value,
                "DeleteList": params.configData.value.removedIds,
                "AttrList":
                    params.configData.value.specification.map(e => {
                        return {
                            AttributeName: e.name,
                            Id: e.Id,
                            ItemList: e.tags.map(es => {
                                return {
                                    Id: es.value,
                                    AttributeValue: es.label
                                }

                            }),
                            DeleteList: e.removedItemsIds
                        }
                    })
            }

            Request({
                url: "/PPE/EditEquBasicInfo",
                method: 'post',
                data: model
            }).then(res => {
                params.messageTest.value.success(res.Msg);
             
                params.templateOpen.value = false
                methods.getTableList(true)
                params.edituploadList.value=[]

    


            })

        },


        AddEquBasicInfo: () => {

            for (let list of params.configData.value.specification) {

                if (!list.name) {
                    return  params.messageTest.value.info('请检查规格名称是否全部填写');
                } else if (list.tags.length == 0) {
                  return    params.messageTest.value.info('请检查规格是否全部添加');
                }

            }
    
            let subobj = {
                TypeId: params.configData.value.type,
                ProductName: params.configData.value.name,
                Unit: params.configData.value.unit,
                Remark: params.configData.value.Remark,
                Description: params.configData.value.Description,
                AttrList: params.configData.value.specification.map(e => {
                    return {
                        AttributeName: e.name,
            
                        ItemList: e.tags.map(es => es.label),

                    }
                }),
         
                FileList: params.uploadImg.value.fileList.map(e => e.FileId),

            }





            Request({
                url: "/PPE/AddEquBasicInfo",
                method: 'post',
                data: subobj
            }).then(res => {
                params.messageTest.value.success(res.Msg);

                params.templateOpen.value = false
                methods.getTableList(true)

                
            })

        },
        handleChange: (info) => {
            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: "/download/uploadfile?Path=PPE/Basic",
                    method: 'post',
                    data: formData
                }).then(res => {

                    let item = params.uploadImg.value.fileList.find(e => e.uid == res.Data[0].uid)
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                    item.name = res.Data[0].FileName
                    params.uploadLock.value = false

                    if (params.opType.value == 1) {


                        params.edituploadList.value.push(res.Data[0].FileId)

                    }
            

                    //edituploadList

                })
            }
       

        },


        handleOk: () => {
            params.proxy.value.$refs.tc.click()
    /*        methods.testclick()*/
            if (params.opType.value == 2) {
                params.templateOpen.value = false
            } else {
                params.proxy.value.$refs.AddOrEditForm.validate()
                    .then(() => {
                        if (params.opType.value == 0) {
                            methods.AddEquBasicInfo()
                        } else {
                            methods.EditEquBasicInfo()
                        }
                    }).catch(err => {

                    })
            }
            

         
        },
        scrollt: () => {
            setTimeout(() => {
                // 判断是否滚动到底部
                if (params.proxy.value.$refs.scrollt.scrollTop + params.proxy.value.$refs.scrollt.clientHeight >= params.proxy.value.$refs.scrollt.scrollHeight) {
                    params.shadowShow.value = false
                } else {
                    params.shadowShow.value = true
                }
            },400)
    
        },
        GetEuqTypeList: () => {
            Request({
                url: "/PPE/GetEuqTypeList",
                method: 'post',
        
            }).then(res => {
                console.log(res)
                params.configData.value.options = res.Data.map(e => {
                    return {
                        label: e.TypeName,
                        value: e.Id
                    }
                })

            })
        },
        init: () => {
                        getBrowserInfo().catch(err => { console.log(err) })
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });



            params.pagination.value.loading = true

            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/account/createjwttoken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                Storage.set('token', res.Data,true)
                methods.getTableList(true)

                methods.GetEuqTypeList()


         

                //setTimeout(() => {
                //    const scrollContainer = document.querySelector('.scroll-container');
                //    const bottomShadow = document.querySelector('.bottom-shadow');

                //    function updateShadow() {
        
                //    }

                //    // 监听滚动事件
                //    scrollContainer.addEventListener('scroll', updateShadow);
                //    // 初始化时检查阴影显示状态
                //    updateShadow();
                //},400)









            })
        },
    }
    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width = "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },
        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end">
                    <a-space>
                        <a-button v-on:click="onSbumit(false)" type="primary" danger>驳回</a-button>
                        <a-button v-on:click="onSbumit(true)" type="primary">通过</a-button>
                        <a-button v-on:click="onBack">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition